package com.wash.shoes.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wash.shoes.entity.FactoryAreaConfigPo;
import com.wash.shoes.mapper.FactoryAreaConfigMapper;
import com.wash.shoes.request.FactoryDispatchRequest;
import com.wash.shoes.service.FactoryAreaConfigService;

import io.jsonwebtoken.lang.Collections;
import lombok.Data;
import lombok.RequiredArgsConstructor;

@Service
@Data
@RequiredArgsConstructor
public class FactoryAreaConfigServiceImpl extends ServiceImpl<FactoryAreaConfigMapper, FactoryAreaConfigPo>
    implements FactoryAreaConfigService {

    /**
     * 配置工厂覆盖区域
     *
     * @param factoryId 工厂id
     * @param data 配置数据
     * @return
     */
    @Override
    @Transactional
    public boolean dispatch(String factoryId, List<FactoryDispatchRequest.FactoryDispatchConfigRecord> data) {
        // 先移除旧数据
        remove(new LambdaQueryWrapper<FactoryAreaConfigPo>().eq(FactoryAreaConfigPo::getFactoryId, factoryId));
        if (Collections.isEmpty(data)) {
            return true;
        }
        List<FactoryAreaConfigPo> data1 = new ArrayList<>();
        data.stream().forEach(e -> {
            e.getRecords().stream().forEach(e1 -> {
                FactoryAreaConfigPo po = new FactoryAreaConfigPo();
                po.setFactoryId(factoryId);
                po.setBrandId(e.getBrandId());
                po.setProvinces(e1.getProvinces());
                po.setCity(e1.getCity());
                po.setCountry(e1.getCountry());
                po.setCode(e1.getCode());
                po.setStatus(1);// 默认设置启用
                data1.add(po);
                // this.saveOrUpdate(po);
            });
        });

        return saveBatch(data1);
    }
}